package manager

import event.MqttChangedEvent
import ext.log
import org.eclipse.paho.client.mqttv3.*
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import task.PayResultTask
import task.RefreshSellTask
import task.UpdateTempValueTask
import java.nio.charset.Charset

object MQTTManager : MqttCallback, Runnable {

    private const val ID_PAY_RESULT = "paysucces"
    private const val ID_PUSH_PRICE = "pushprice"
    private const val ID_TEMPER_SET = "setTemperature" // 温度报警
    private const val ID_TEMPER_CONTROL = "controlTemperature" //温度控制
    private const val ID_STATUS = "status" // 再售, 停售
    private const val ID_RESTART = "restart"
    private const val ID_MCU_UPDATE = "updateclientAndlower" // 客户端 单片机升级
    private const val ID_ADV = "setAdvertise"
    private const val ID_ORDER = "pushOrder"

    //private const val Host = "tcp://test.hontech-rdcenter.com:1883"
    //private const val Host = "tcp://106.12.198.37:1883" // 百度云
    //private const val Host = "tcp://106.15.126.180:1883" // 阿里云
    private const val Host = "tcp://news.hontech-rdcenter.com:1883" // 阿里云
    private const val UserName = "xdh"
    private const val Password = "xdh123"

    private val client = MqttClient(Host, AppManager.MacAddress, null)

    fun connectToServer() {
        TaskManager.DelayHandler.post(this)
    }

    override fun run() {
        try {
            log("开始连接MQTT", "MQTT连接")
            connect()
        } catch (e: Exception) {
            e.printStackTrace()
            EventBus.getDefault().post(MqttChangedEvent(false))
            TaskManager.DelayHandler.postDelayed(this, 10000)
        }
    }

    private fun connect() {
        if (client.isConnected) {
            EventBus.getDefault().post(MqttChangedEvent(true))
            log("MQTT已经连接", "MQTT连接")
            return
        }
        val options = MqttConnectOptions()
        options.userName = UserName
        options.password = Password.toCharArray()
        options.keepAliveInterval = 10
        options.isCleanSession = true
        options.mqttVersion = MqttConnectOptions.MQTT_VERSION_3_1_1
        client.setCallback(this)
        client.connect(options)
        log("MQTT连接成功", "MQTT连接状态")
        client.subscribe(AppManager.MacAddressTopic, 2)
        EventBus.getDefault().post(MqttChangedEvent(true))
    }

    override fun messageArrived(topic: String, message: MqttMessage) {
        val messageStr = String(message.payload, Charset.forName("utf-8"))
        log("MQTT消息:$topic--------$messageStr")
        AppManager.checkApplication()
        if (topic == AppManager.MacAddressTopic) {
            onReceive(messageStr)
        }
    }

    override fun connectionLost(cause: Throwable) {
        log("MQTT连接断开", "MQTT连接断开")
        cause.printStackTrace()
        EventBus.getDefault().post(MqttChangedEvent(false))
        TaskManager.DelayHandler.postDelayed(this, 10000)
    }

    override fun deliveryComplete(token: IMqttDeliveryToken) {
        log("MQTT消息发送成功", "MQTT发送")
    }

    private fun onReceive(msg: String) {
        try {
            val json = JSONObject(msg)
            val id = json.optString("id")

            when (id) {
                ID_PAY_RESULT -> {
                    val param = json.optJSONObject("param")
                    TaskManager.DelayHandler.post(PayResultTask(param))
                }

                ID_PUSH_PRICE -> {
                    WaresManager.refreshAsync()
                }

                ID_TEMPER_SET -> {
                    TaskManager.DelayHandler.post(UpdateTempValueTask())
                }

                ID_TEMPER_CONTROL -> {
                    HeatManager.refreshAsync()
                }

                ID_RESTART -> AppManager.resetSystem()

                ID_STATUS -> {
                    TaskManager.DelayHandler.post(RefreshSellTask())
                }

                ID_MCU_UPDATE -> {
                    val param = json.optJSONObject("param")
                    VersionManager.updateWithServer(param)
                }

                ID_ADV -> {
                    AdvertisingManager.refreshWithAsync()
                }

                ID_ORDER -> {
                    log("订单号:$msg")
                }

            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}